<template>
	<view class="top_horizontal_line"></view>
	<view class="pets_details_box">
		<view class="order_status_box">
			<view class="order_status">{{ getStatusText(orderInfo.status) }}</view>
			<view class="order_tips" v-if="orderInfo.status === 0">
				订单将在
				<text class="countdowns_time">{{ countdowns.time }}</text>
				后失效，请及时支付。
			</view>
			<view class="order_tips" v-else>{{ getStatusTipsText(orderInfo.status) }}</view>
			<view class="order_tips" v-if="orderInfo.refuseReason">原因：{{ orderInfo.refuseReason }}</view>
		</view>
		<view class="order_info_box">
			<template v-if="orderInfo.newOrderFlag == 1">
				<template v-if="identity === 1">
					<view class="order_data_info_box" v-if="studio.id == orderInfo.studioId">
						<view class="order_data_info" v-if="getReceivingSharingStatus">
							<view class="order_data_label">工作室接单收入：</view>
							<view class="order_data_value xjs-weight-bold">¥{{ cancelStatus ? "0.00" : orderInfo.studioSharing }}</view>
						</view>
						<view class="order_data_info" :class="getReceivingSharingStatus ? 'user_income' : ''">
							<view class="order_data_label">
								<image class="studio_img" :src="orderInfo.petsitterAvatar"></image>
								<view>{{ orderInfo.petsitterNickName }}（服务陪宠师）</view>
							</view>
							<view class="order_data_value xjs-weight-bold">¥{{ cancelStatus ? "0.00" : orderInfo.income }}</view>
						</view>
					</view>
					<view class="order_data_info_box" v-if="studio.id == orderInfo.refereeStudioId">
						<view class="order_data_info" v-if="getPromotionSharingStatus">
							<view class="order_data_label">工作室推广收入：</view>
							<view class="order_data_value xjs-weight-bold">¥{{ cancelStatus ? "0.00" : orderInfo.originStudioSharing }}</view>
						</view>
						<view class="order_data_info" :class="getPromotionSharingStatus ? 'user_income' : ''">
							<view class="order_data_label">
								<image class="studio_img" :src="orderInfo.promotionUserAvatar"></image>
								<view>{{ orderInfo.promotionUserNickName }}（推广人）</view>
							</view>
							<view class="order_data_value xjs-weight-bold">¥{{ cancelStatus ? "0.00" : orderInfo.promotionSharing }}</view>
						</view>
					</view>
				</template>
				<template v-if="identity === 0">
					<view class="order_data_info_box" v-if="orderInfo.promotionUserId == userInfo.id">
						<view class="order_data_info">
							<view class="order_data_label">我的推广收入：</view>
							<view class="order_data_value xjs-weight-bold">¥{{ cancelStatus ? "0.00" : orderInfo.promotionSharing }}</view>
						</view>
					</view>
					<view class="order_data_info_box" v-if="orderInfo.petsitterUserId == userInfo.id">
						<view class="order_data_info">
							<view class="order_data_label">我的服务收入：</view>
							<view class="order_data_value xjs-weight-bold">¥{{ cancelStatus ? "0.00" : orderInfo.income }}</view>
						</view>
					</view>
				</template>
			</template>
			<view class="pet_companion_teacher_box">
				<view class="pet_teacher_title">陪宠师信息</view>
				<view class="pet_teacher_info_box">
					<image class="pet_teacher_img" :src="orderInfo.petsitterAvatar"></image>
					<view class="pet_teacher_info">
						<view class="pet_teacher_name">{{ orderInfo.petsitterNickName }}</view>
						<view class="pet_teacher_tel">{{ orderInfo.petsitterRealName }}｜{{ orderInfo.petsitterPhone }}</view>
					</view>
				</view>
			</view>
			<view class="pet_companion_teacher_box">
				<view class="pet_teacher_title">宠物主信息</view>
				<view class="pet_teacher_info_box">
					<image class="pet_teacher_img" :src="orderInfo.userAvatar"></image>
					<view class="pet_teacher_info">
						<view class="pet_teacher_name">{{ orderInfo.userNickName }}</view>
						<view class="pet_teacher_tel">
							<template v-if="shouldShowFullData">{{ orderInfo.userPhone }}</template>
							<template v-else>{{ getMaskedPhoneNumber(orderInfo.userPhone) }}</template>
						</view>
					</view>
				</view>
			</view>

			<view class="order_item_box">
				<view class="association_tips">关联日服务订单</view>
				<view class="order_info_status_box">
					<view class="name_status">
						<view class="name_transfer">
							<image class="user_avatar_pic" :src="orderInfo?.orderDetailVO?.userAvatar"></image>
							<view class="studio_name">{{ orderInfo?.orderDetailVO?.userNickName }}</view>
						</view>
						<view class="order_status">{{ getMainStatusText(orderInfo?.orderDetailVO?.status) }}</view>
					</view>
					<view class="order_date">订单号：{{ orderInfo?.orderDetailVO?.id }}</view>
				</view>
				<view class="studio_name_text">{{ orderInfo?.orderDetailVO?.studioName }}</view>
				<view class="order_server_info">
					<scroll-view class="multiple_specs_scroll" scroll-x="true" v-if="orderInfo?.orderGoodsSkuVOSAll?.length > 1">
						<view class="server_info_box" v-for="val in orderInfo.orderGoodsSkuVOSAll" :key="val.skuId">
							<image class="server_img" :src="val.goodsAvatar"></image>
							<view class="specs_box">{{ val.goodsName }}</view>
							<view class="server_price">×{{ val.serviceDays }}</view>
						</view>
					</scroll-view>
					<view class="server_info_box" v-if="orderInfo?.orderGoodsSkuVOSAll?.length == 1">
						<image class="server_img" :src="orderInfo?.orderGoodsSkuVOSAll[0]?.goodsAvatar"></image>
						<view class="name_price">
							<view class="server_name">{{ orderInfo?.orderGoodsSkuVOSAll[0]?.goodsName }}</view>
							<view class="specs_price">
								<text class="server_specs">{{ orderInfo?.orderGoodsSkuVOSAll[0]?.serviceTime }} | ¥{{ orderInfo?.orderGoodsSkuVOSAll[0]?.price }}</text>
								<!--								<text class="server_price"></text>-->
							</view>
						</view>
					</view>
					<view class="order_price_box">
						<view class="order_price">¥{{ orderInfo?.orderDetailVO?.payAmount }}</view>
						<view class="pay_text">{{ getPayText(orderInfo?.orderDetailVO?.status) }}</view>
					</view>
				</view>
				<view class="order_other_info_box">
					<view class="other_info_item">
						<view class="other_label">宠物{{ orderInfo?.orderDetailVO?.petNum }}只</view>
						<view class="other_value">
							<text v-for="(val, valIndex) in orderInfo?.orderDetailVO?.petList" :key="valIndex">
								{{ val.petNickName }}({{ getPetTypeText(val.type) }})
								<text class="m_l_r_8" v-if="valIndex < orderInfo?.orderDetailVO?.petList.length - 1">|</text>
							</text>
						</view>
					</view>
					<view class="other_info_item">
						<view class="other_label">服务时间</view>
						<view class="other_value">
							{{ orderInfo?.orderDetailVO?.serviceStartTime?.substring(0, 10) }}&nbsp;{{ handleDoorTime(orderInfo?.orderDetailVO?.doorTime) }}
						</view>
					</view>
					<view class="other_info_item">
						<view class="other_label">服务地址</view>
						<view class="other_value">
							<template v-if="shouldShowFullData">
								{{ orderInfo?.orderDetailVO?.address }}
							</template>
							<template v-else>
								{{ getMaskedAddress(orderInfo?.orderDetailVO?.address) }}
							</template>
						</view>
					</view>
				</view>
			</view>
			<view class="value_added_services_box" v-if="orderInfo?.orderGoodsSkuVOS?.length">
				<view class="add_title">增值服务</view>
				<view class="add_order_list_box">
					<view class="add_order_item" v-for="item in orderInfo.orderGoodsSkuVOS" :key="item.skuId">
						<image class="add_server_img" :src="item.goodsAvatar"></image>
						<view class="add_server_info">
							<view class="add_server_name">{{ item.goodsName }}</view>
							<view class="add_server_price">
								<view class="price">￥{{ item.price }}/次</view>
								<view class="times">×{{ item.serviceDays }}</view>
							</view>
							<view class="add_server_pets" v-if="item?.petVOList?.length || (orderType == -1 ? item?.serviceDateStr : item?.serviceDate)">
								<template v-if="item?.petVOList?.length">
									<text v-for="(val, i) in item.petVOList" :key="i">
										<template v-if="orderType == -1">
											<template v-if="item?.serviceDateStr?.split(',').length">
												<text class="pet_name_date" v-for="(itemVal, itemValIndex) in item?.serviceDateStr?.split(',')" :key="itemValIndex">
													{{ val.petNickName }}({{ itemVal }})
												</text>
											</template>
											<text class="pet_name_date" v-else>
												{{ val.petNickName }}
											</text>
										</template>
										<text class="pet_name_date" v-else>{{ val.petNickName }}({{ item?.serviceDate?.substring(0, 10) }})</text>
									</text>
								</template>
								<template class="" v-else>
									<template v-if="orderType == -1">
										<text class="pet_name_date" v-for="(itemVal, itemValIndex) in item?.serviceDateStr?.split(',')" :key="itemValIndex">
											{{ itemVal }}
										</text>
									</template>
									<text class="pet_name_date" v-else>{{ item?.serviceDate?.substring(0, 10) }}</text>
								</template>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="order_data_info_box" v-if="shouldShowFullData">
				<view class="order_data_info order_total">
					<view class="order_data_label">{{ getPayText(orderInfo.status) }}：</view>
					<view class="order_data_value">¥{{ Number(orderInfo.payAmount) }}</view>
				</view>
			</view>
			<view class="order_data_info_box" v-if="![0, 2, 3, 5, 6, 7].includes(orderInfo.status) && orderInfo.newOrderFlag == 2">
				<view class="income_structure">本单收益构成</view>
				<template v-if="identity === 1">
					<view class="order_data_info">
						<view class="order_data_label">平台抽成</view>
						<view class="order_data_value">¥{{ orderInfo.commissionSharing }}</view>
					</view>
					<view class="order_data_info">
						<view class="order_data_label">工作室收益</view>
						<view class="order_data_value">¥{{ orderInfo.studioSharing }}</view>
					</view>
				</template>
				<view class="order_data_info">
					<view class="order_data_label">陪宠师收益</view>
					<view class="order_data_value">¥{{ orderInfo.income }}</view>
				</view>
				<view class="order_data_info" v-if="orderInfo.promotionUserId && orderInfo.promotionSharing && identity === 1">
					<view class="order_data_label">分享人收益</view>
					<view class="order_data_value">¥{{ orderInfo.promotionSharing }}</view>
				</view>
			</view>
			<view class="order_data_info_box" v-if="orderType == -1">
				<view class="order_data_info">
					<view class="order_data_label">关联总订单</view>
					<view class="order_data_value">{{ orderInfo.joinId }}</view>
				</view>
			</view>
			<view class="order_data_info_box">
				<view class="order_data_info">
					<view class="order_data_label">订单号</view>
					<view class="order_data_value">
						<view class="">{{ orderInfo.id }}</view>
						<view class="dividing_line"></view>
						<view class="copy_btn" @click="onCopy(orderInfo.id)">复制</view>
					</view>
				</view>
				<view class="order_data_info">
					<view class="order_data_label">创建时间</view>
					<view class="order_data_value">{{ orderInfo.createTime }}</view>
				</view>
				<view class="order_data_info" v-if="orderInfo.payTime">
					<view class="order_data_label">支付时间</view>
					<view class="order_data_value">{{ orderInfo.payTime }}</view>
				</view>
				<view class="order_data_info" v-if="orderInfo.acceptTime">
					<view class="order_data_label">接单时间</view>
					<view class="order_data_value">{{ orderInfo.acceptTime }}</view>
				</view>
				<view class="order_data_info" v-if="orderInfo.confirmTime">
					<view class="order_data_label">到达时间</view>
					<view class="order_data_value">{{ orderInfo.confirmTime }}</view>
				</view>
				<view class="order_data_info" v-if="orderInfo.finishTime">
					<view class="order_data_label">完成时间</view>
					<view class="order_data_value">{{ orderInfo.finishTime }}</view>
				</view>
				<view class="order_data_info" v-if="orderInfo.cancelTime">
					<view class="order_data_label">取消时间</view>
					<view class="order_data_value">{{ orderInfo.cancelTime }}</view>
				</view>
			</view>
		</view>
		<view class="footer_btn_box" v-if="pageSource != 1">
			<template v-if="orderType == -1 && userInfo.id == orderInfo.petsitterUserId">
				<view class="xjs-btn-primary-plain hollow_btn btn_mg" v-if="[1, 8].includes(orderInfo.status)" @click="handleOpenPop()">拒绝接单</view>
				<view class="xjs-btn-primary solid_btn btn_mg" v-if="[1, 8].includes(orderInfo.status)" @click="handleAccept(orderInfo)">立即接单</view>
			</template>
			<template v-if="orderType == 0 && userInfo.id == orderInfo.petsitterUserId">
				<view class="xjs-btn-primary-plain hollow_btn btn_mg" v-if="[1].includes(orderInfo.status)" @click.stop="handleCancel(orderInfo)">取消订单</view>
				<!--				<view class="xjs-btn-primary solid_btn btn_mg" v-if="[1].includes(orderInfo.status)" @click.stop="handleConfirmArrival(orderInfo)">我已到达</view>-->
				<!--				<view class="xjs-btn-primary solid_btn btn_mg" v-if="[2].includes(orderInfo.status)" @click.stop="handleDailyService(orderInfo)">服务完成</view>-->
				<view class="xjs-btn-primary solid_btn btn_mg" @click.stop="contactUser(orderInfo)">联系客户</view>
			</template>
		</view>
	</view>
	<petsInfoPop ref="petsInfoRef"></petsInfoPop>
	<paymentPopup ref="paymentPopupRef" @confirm="paySuccess" @fail="payFail"></paymentPopup>
	<uni-popup ref="refusePopupRef" type="bottom" :is-mask-click="false">
		<view class="refuse_pop">
			<view class="pop_title_box">
				<view class="pop_title">确定拒绝接单吗？</view>
				<uni-icons @click="handleClosePop()" class="closeempty_icon" type="closeempty" size="26"></uni-icons>
			</view>
			<view class="refuse_reason_box">
				<view class="refuse_title">原因：</view>
				<view class="reason_item_box">
					<textarea placeholder-style="color:#CACCCC;" class="refuse_textarea" v-model="reasonInfo.reason" maxlength="50" placeholder="输入原因"></textarea>
				</view>
			</view>
			<view class="footer_btn_box">
				<view class="xjs-btn-primary confirm_btn" @click="handleConfirm()">确认</view>
			</view>
		</view>
	</uni-popup>
	<image @tap="handlekf('400-154-1313')" class="kefu" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-62.png" mode="widthFix"></image>
</template>
<script setup>
import { ref, reactive, onUnmounted, computed } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { formatTime, birthToAgeDiff } from "@/hooks/useFunction";
import petsInfoPop from "../components/petsInfoPop/index.vue";
import api from "@/api/index";
import { payment } from "@/hooks/usePay";
import BigNumber from "bignumber.js";
import { useStudioStoreToRefs } from "@/store/useStudioStore";
import { useUserStoreToRefs } from "@/store/useUserStore";

let { studioBalance, studio, identity } = useStudioStoreToRefs();
let { userInfo } = useUserStoreToRefs();

let orderId = ref();
let orderType = ref();
let pageSource = ref(""); // 1 收益

let reasonInfo = reactive({
	id: "",
	reason: ""
});

let orderInfo = reactive({});
let refusePopupRef = ref();

const handleOpenPop = () => {
	refusePopupRef.value.open();
};
const handleClosePop = () => {
	refusePopupRef.value.close();
	reasonInfo.reason = "";
};
const handleConfirm = async () => {
	if (reasonInfo.reason.trim() == "") {
		uni.showToast({
			title: "请输入拒绝原因",
			icon: "none"
		});
		return;
	}
	const res = await api({
		method: "post",
		url: `/mall/order/refuse`,
		data: {
			orderId: orderId.value,
			refuseReason: reasonInfo.reason
		}
	});
	if (res.code == 0) {
		uni.showToast({
			title: "拒绝成功",
			icon: "none"
		});
	}
	handleClosePop();
	await getOrderDetail();
};
// 联系客服
const handlekf = (item) => {
	uni
		.showModal({
			title: "提示",
			content: "客服上班时间：周一到周六 09:30~18:30",
			confirmText: "确定呼叫"
		})
		.then((e) => {
			console.log(e);
			if (e.confirm) {
				uni.makePhoneCall({
					phoneNumber: item
				});
			}
		});
};
const getMaskedPhoneNumber = (phoneNumber) => {
	if (!phoneNumber) return "";
	const regex = /^(\d{3})\d*(\d{4})$/;
	return phoneNumber.replace(regex, "$1****$2");
};
const getMainStatusText = (status) => {
	switch (status) {
		case 0:
			return "待接单";
		case 1:
			return "待服务";
		case 2:
			return "服务中";
		case 3:
			return "已完成";
		case 4:
		case 5:
			return "已取消";
		case 6:
			return "待付款";
		default:
			return "";
	}
};
const getStatusText = (status) => {
	if (orderType.value == -1) {
		switch (status) {
			case 0:
				return "待付款";
			case 1:
			case 8:
				return "待接单";
			case 2:
			case 3:
				return "已接单";
			case 4:
				return "已完成";
			case 5:
			case 6:
			case 7:
				return "已取消";
			default:
				return "";
		}
	} else {
		switch (status) {
			case 0:
				return "待接单";
			case 1:
				return "待服务";
			case 2:
				return "服务中";
			case 3:
				return "已完成";
			case 4:
			case 5:
				return "已取消";
			case 6:
				return "待付款";
			default:
				return "";
		}
	}
};
const handleDoorTime = (data) => {
	if (data) {
		let dataArr = data?.split("~");
		if (dataArr[0] == "00:00" && dataArr[1] == "00:00") {
			return "无时间段要求";
		} else {
			return data;
		}
	} else {
		return data;
	}
};
const getStatusTipsText = (status) => {
	// --总单订单状态: 0-待付款; 1-待接单; 2-待服务; 3-服务中; 4-已完成; 5-已关闭; 6-已取消; 7-已退款 8-待派单
	// --日单状态:    1-待服务; 2-服务中 3-已完成(已结算); 4-已退款; 5-已关闭
	if (orderType.value == -1) {
		switch (status) {
			case 0:
				return "等待客户付款";
			case 1:
				return "等待陪宠师接单";
			case 2:
				return "";
			case 3:
				return "陪宠师已经到达，开始服务";
			case 4:
				return "陪宠师已经完成服务";
			case 5:
				return "超时未支付";
			case 6:
			case 7:
				if (orderInfo.cancelType == 1) {
					return "用户主动取消";
				} else if (orderInfo.cancelType == 2) {
					return "店长取消";
				} else if (orderInfo.cancelType == 3) {
					return "陪宠师取消";
				} else {
					return "订单已取消";
				}
			case 8:
				return "请及时派单";
			default:
				return "";
		}
	} else {
		switch (status) {
			case 1:
				return "请陪宠师及时和宠物主沟通上门时间以及其他细节";
			case 2:
				return "陪宠师已经到达，开始服务";
			case 3:
				return "陪宠师已经完成服务";
			case 4:
			case 5:
				if (orderInfo.cancelType == 1) {
					return "用户主动取消";
				} else if (orderInfo.cancelType == 2) {
					return "店长取消";
				} else if (orderInfo.cancelType == 3) {
					return "陪宠师取消";
				} else {
					return "";
				}
			default:
				return "";
		}
	}
};

const getPetTypeText = (type) => {
	switch (type) {
		case 0:
			return "猫";
		case 1:
			return "狗";
		default:
			return "其他";
	}
};
// 交接方式: 0-有人在家;1-密码;2-丰巢存件;3-其他; 4-面交; 5-快递; 6-闪送; 7-放在指定位置;
const getHandoverTypeText = (status, type) => {
	switch (status) {
		case 0:
			return "有人在家";
		case 1:
			return "密码锁";
		case 2:
			return "丰巢存件";
		case 3:
			if (type === 1) {
				return orderInfo.handoverRemarks;
			} else if (type === 2) {
				return orderInfo.returnRemarks;
			} else {
				return "";
			}
		case 4:
			return "面交";
		case 5:
			return "快递";
		case 6:
			return "闪送";
		case 7:
			return "放在指定位置";
		default:
			return "";
	}
};
const getPayTypeText = (status) => {
	switch (status) {
		case 1:
			return "抖音支付";
		case 2:
			return "支付宝";
		case 3:
			return "微信支付";
		default:
			return "";
	}
};
const getPayText = (type) => {
	switch (type) {
		case 4:
		case 5:
			return "合计";
		default:
			return "实付";
	}
};

const viewOrderProgress = async (item) => {
	uni.navigateTo({
		url: `/pages/petsOrder/orderProcess/index?orderId=${item.id}&studioId=${item.studioId}`
	});
};
const previewImages = (currentIndex, urls) => {
	uni.previewImage({
		current: currentIndex,
		urls
	});
};
const shouldShowFullData = computed(() => {
	return (pageSource.value === "1" && userInfo.value.id === orderInfo.petsitterUserId) || pageSource.value !== "1";
});
const cancelStatus = computed(() => {
	if (orderType.value == -1) {
		return [5, 6, 7].includes(orderInfo.status);
	}
	if (orderType.value == 0) {
		return [4, 5].includes(orderInfo.status);
	}
});
const getReceivingSharingStatus = computed(() => {
	let addOrder = [];
	let receivingSharingStatus = false;
	orderInfo?.orderGoodsSkuVOS.forEach((item) => {
		if ([4].includes(item.goodsType)) {
			addOrder.push(item);
		}
	});
	addOrder.forEach((item) => {
		if (item.receivingSharingStatus == 1) {
			receivingSharingStatus = true;
		}
	});
	return receivingSharingStatus;
});
const getPromotionSharingStatus = computed(() => {
	let addOrder = [];
	let promotionSharingStatus = false;
	orderInfo?.orderGoodsSkuVOS.forEach((item) => {
		if ([4].includes(item.goodsType)) {
			addOrder.push(item);
		}
	});
	addOrder.forEach((item) => {
		if (item.promotionSharingStatus == 1) {
			promotionSharingStatus = true;
		}
	});
	return promotionSharingStatus;
});
// 隐藏地址中除省市区的其他信息
const getMaskedAddress = (address) => {
	if (!address) return "";

	// 定义省、市、区的正则表达式
	// const provinceRegex = /^(.+?[省|自治区|特别行政区|市])/;
	const cityRegex = /([^省|自治区|特别行政区]+?[市|自治州|地区|盟])/;
	const districtRegex = /([^市]+?[区|县|旗])/;

	// let provinceMatch = address.match(provinceRegex);

	let cityMatch = address.match(cityRegex);
	let districtMatch = address.match(districtRegex);
	// console.log(provinceMatch, "provinceMatch");
	console.log(cityMatch, "cityMatch");
	console.log(districtMatch, "districtMatch");

	// let province = provinceMatch ? provinceMatch[1] : "";
	let city = cityMatch ? cityMatch[1] : "";
	let district = districtMatch ? districtMatch[1] : "";

	// 计算省市区总长度
	const prefixLength = city.length + district.length;
	// const prefixLength = province.length + city.length + district.length;
	// 获取剩余部分并用 * 替换
	const maskedPart = "*".repeat(Math.max(0, address.length - prefixLength));

	return city + district + maskedPart;
};
const getOrderDetail = async () => {
	let url = "";
	if (orderType.value == -1) {
		url = `/mall/order/detail/${orderId.value}`;
	} else {
		url = `/mall/order/order-detail/dayOrderDetail?id=${orderId.value}`;
	}
	const res = await api({
		method: "get",
		url: url,
		contentType: "json"
	});
	if (res.code === 0) {
		res.data.extAmountObj = JSON.parse(res.data?.extAmountJson) || {};
		Object.assign(orderInfo, res.data);
		if (orderInfo.status === 0) {
			if (orderInfo.orderAutoCancelTime) {
				const duration = formatTime(orderInfo.orderAutoCancelTime).getTime() - Date.now();
				if (duration > 0) {
					onCountdownCheck();
				}
			}
		}
	}
};

let petsInfoRef = ref();
const viewPetsInfo = () => {
	petsInfoRef.value.handleOpenPop(JSON.stringify(orderInfo.petList));
};
// 店长取消订单
const handleCancelAllOrder = async (item) => {
	uni.showModal({
		title: "确定取消订单吗？",
		content: "注意：确定后订单将关闭",
		success: async (res) => {
			if (res.confirm) {
				uni.navigateTo({
					url: `/pages/studioOrders/cancellationReason/index?orderId=${item.id}&orderType=${table.orderType}`
				});
			}
		}
	});
};
// 拒绝，转单
const handleRefuse = async (item) => {
	if (item.type === 1) {
		handleOpenPop();
	} else {
		uni.showModal({
			title: "确定拒绝接单/转单吗？",
			content: "注意：提交后订单将转派给其他陪宠师进行接单",
			success: async (res) => {
				if (res.confirm) {
					const res = await api({
						method: "post",
						url: `/mall/order/refuse`,
						data: {
							orderId: item.id
						}
					});
					if (res.code == 0) {
						uni.showToast({
							title: "转单成功"
						});
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none"
						});
					}
					await onDataInit();
				}
			}
		});
	}
};
// 联系用户
const contactUser = () => {
	uni.navigateTo({
		url: `/pages/im/message/index?id=${orderInfo.userId}&username=${orderInfo.userNickName}&avatar=${orderInfo.userAvatar}`
	});
};
// 立即接单
const handleAccept = async (item) => {
	uni.showModal({
		title: "提示",
		content: "确定接单？",
		success: async (res) => {
			if (res.confirm) {
				const res = await api({
					method: "post",
					url: `/mall/order/acceptV2`,
					data: {
						id: item.id
					}
				});
				if (res.code == 0) {
					uni.navigateTo({
						url: `/pages/myStudio/studio/dispatchSuccess/index?type=receivingOrders&id=${item.userId}&serviceDays=${item.serviceDays}&userNickName=${item.userNickName}&userAvatar=${item.userAvatar}`
					});
				} else {
					uni.showToast({
						title: res.msg,
						icon: "none"
					});
				}
			}
		}
	});
};
const transferOrderCheck = async (item) => {
	return new Promise(async (resolve, reject) => {
		try {
			const res = await api({
				method: "get",
				url: `/mall/order/transferOrderCheck`,
				data: {
					orderId: item.id
				}
			});
			resolve(res);
		} catch (e) {
			reject(e);
		}
	});
};
const handleTransferOrder = async (item) => {
	const checkRes = await transferOrderCheck(item);
	if (checkRes.data == 0) {
		uni.navigateTo({
			url: `/pages/myStudio/studio/selectDispatch/index?id=${item.id}&petsitterType=${item.petsitterType}&serviceDays=${item.serviceDays}&status=${item.status}`
		});
	} else if (checkRes.data == 1) {
		uni.showModal({
			title: "温馨提示",
			content: "该单已被同城所有工作室拒绝过了\n" + "您可以自己接单或取消订单",
			showCancel: false,
			confirmText: "好的",
			success: async (res) => {}
		});
	} else if (checkRes.data == 2) {
		uni.showModal({
			title: "温馨提示",
			content: "本订单所在城市暂无工作室",
			showCancel: false,
			confirmText: "好的",
			success: async (res) => {}
		});
	}
};

// 立即派单
const handleDispatch = async (item) => {
	const res = await api({
		method: "get",
		url: `/mall/studio/petsitter-team/dispatchPage`,
		data: {
			page: 1,
			limit: 20,
			orderId: item.id
		}
	});
	if (res.code == 0) {
		uni.navigateTo({
			url: `/pages/myStudio/studio/selectDispatch/index?id=${item.id}&petsitterType=${item.petsitterType}&serviceDays=${item.serviceDays}&status=${item.status}`
		});
	} else {
		uni.showModal({
			title: "温馨提示",
			content: res.msg,
			showCancel: false,
			confirmText: "好的"
		});
	}
};

const paymentPopupRef = ref(null);
const handlePay = async () => {
	// #ifndef MP-TOUTIAO
	// 该弹窗用于非抖音支付，包括微信、支付宝等
	// 使用该弹窗时需要添加条件编译，避免抖音支付调用该弹窗
	// 组件全局注册，可以不用import引入

	// data 所需参数
	// checkOrderType: 订单检验和支付成功后续功能 petsService 宠物服务，具体名称查询 pages/share/aliPayForQR/index.vue 页面的 checkList
	// payAmount: 订单金额
	// payBusinessType: 支付业务类型 1-服务订单支付  2保证金支付
	// orderId: 订单id， payBusinessType为2时可不传

	// <paymentPopup ref="paymentPopupRef" @confirm='xxx' />
	await getOrderDetail();
	await paymentPopupRef.value.open({
		orderId: orderInfo.id,
		payAmount: orderInfo.payAmount,
		payBusinessType: 1,
		checkOrderType: "petsService"
	});
	// #endif

	// #ifdef MP-TOUTIAO
	let res = await payment({
		payType: 1,
		orderId: orderInfo.id,
		payBusinessType: 1,
		amount: orderInfo.payAmount
	});
	if (res) {
		uni.showToast({
			title: "支付成功",
			icon: "none",
			duration: 1000
		});
		setTimeout(async () => {
			await getOrderDetail();
		}, 1000);
	} else {
		uni.showToast({
			title: "支付失败",
			icon: "none",
			duration: 1000
		});
	}
	// #endif
};
// 支付成功
const paySuccess = async (data) => {
	uni.navigateTo({
		url: `/pages/payment/successfulPayment/index?orderId=${data.orderId}`
	});
	paymentPopupRef.value.close();
	await getOrderDetail();
};
// 支付失败
const payFail = async () => {
	paymentPopupRef.value.close();
	await getOrderDetail();
};

// 获取其他待服务日单
const getOtherDayOrder = async (item) => {
	return new Promise(async (resolve, reject) => {
		const res = await api({
			method: "get",
			url: `/mall/order/order-detail/getJoinOrderDetail`,
			data: {
				orderId: item.orderId,
				orderDetailId: item.id
			}
		});
		if (res.code == 0) {
			if (res.data.length > 1) {
				resolve(true);
			} else {
				resolve(false);
			}
		} else {
			reject(false);
		}
	});
};
// 日单取消订单
const handleCancel = async (item) => {
	const res = await getOtherDayOrder(item);
	if (res) {
		uni.navigateTo({
			url: `/pages/studioOrders/cancellationOrder/index?orderId=${item.orderId}&orderDetailId=${item.id}&orderType=${table.orderType}`
		});
	} else {
		uni.showModal({
			title: "确定取消订单吗？",
			content: "注意：确定后订单将关闭",
			success: async (res) => {
				if (res.confirm) {
					uni.navigateTo({
						url: `/pages/studioOrders/cancellationReason/index?orderId=${item.orderId}&orderDetailId=${item.id}&checkedList=${item.id}&orderType=${table.orderType}`
					});
				}
			}
		});
	}
};
// 确认到达
const handleConfirmArrival = async (item) => {
	uni.navigateTo({
		url: `/pages/petsOrder/confirmArriving/index?orderId=${item.id}&studioId=${studio.value.id}`
	});
};
// 上传服务日常
const handleDailyService = async (item) => {
	uni.navigateTo({
		url: `/pages/petsOrder/uploadRoutine/index?orderId=${item.id}`
	});
};

const countdowns = reactive({
	timer: null,
	time: "",
	once: false
});
const onCountdownCheck = () => {
	if (countdowns.timer) clearTimeout(countdowns.timer);
	const duration = formatTime(orderInfo.orderAutoCancelTime).getTime() - Date.now();
	console.log(duration);
	if (duration > 0) {
		if (!countdowns.once) countdowns.once = true;
		countdowns.time = onCountdownTransform(duration);
		countdowns.timer = setTimeout(onCountdownCheck, 1000);
	} else {
		uni.showModal({
			title: "提示",
			content: "订单状态已变更",
			showCancel: false,
			success: () => {
				uni.navigateBack();
			}
		});
		countdowns.time = "";
		getOrderDetail();
	}
};

const onCountdownTransform = (duration) => {
	const hour = Math.floor(duration / (1000 * 60 * 60));
	const minute = Math.floor((duration - hour * 1000 * 60 * 60) / (1000 * 60));
	const seconds = Math.floor((duration % (1000 * 60)) / 1000);
	if (Number(hour) > 0) {
		return `${hour.toString().padStart(2, "0")}时${minute.toString().padStart(2, "0")}分${seconds.toString().padStart(2, "0")}秒`;
	} else if (Number(minute) > 0) {
		return `${minute.toString().padStart(2, "0")}分${seconds.toString().padStart(2, "0")}秒`;
	} else if (Number(seconds) > 0) {
		return `${seconds.toString().padStart(2, "0")}秒`;
	}
};
const onCopy = (id) => {
	uni.setClipboardData({
		data: id
	});
};

onLoad(async (options) => {
	console.log(options);
	orderId.value = options.id;
	orderType.value = options.orderType;
	pageSource.value = options?.pageSource;
});
onShow(async () => {
	await getOrderDetail();
});
onUnmounted(() => {
	if (countdowns.timer) clearTimeout(countdowns.timer);
});
</script>

<style scoped lang="scss">
.pets_details_box {
	width: 100%;
	padding-bottom: calc(constant(safe-area-inset-bottom) + 104rpx + 28rpx);
	padding-bottom: calc(env(safe-area-inset-bottom) + 104rpx + 28rpx);

	.order_status_box {
		position: relative;
		display: flex;
		flex-direction: column;
		width: 100%;
		min-height: 226rpx;
		padding: 48rpx 32rpx;
		padding-bottom: 90rpx;
		box-sizing: border-box;
		background: linear-gradient(180deg, #ff7d9e 18%, #ffb796 100%);
		border-radius: 0rpx 0rpx 40rpx 40rpx;

		.order_status {
			font-weight: bold;
			font-size: 40rpx;
			color: #ffffff;
		}

		.order_tips {
			font-weight: 400;
			font-size: 26rpx;
			color: #ffffff;
			margin-top: 8rpx;

			.countdowns_time {
				color: #1b2120;
			}
		}
	}

	.order_info_box {
		position: relative;
		width: 100%;
		padding: 0 32rpx;
		box-sizing: border-box;
		margin-top: -48rpx;

		.pet_companion_teacher_box {
			width: 100%;
			background: #ffffff;
			border-radius: 24rpx;
			padding: 32rpx;
			box-sizing: border-box;
			margin-bottom: 24rpx;

			.pet_teacher_title {
				font-weight: bold;
				font-size: 26rpx;
				color: #1b2120;
				padding-bottom: 24rpx;
				border-bottom: 1rpx solid #e4e6e6;
			}

			.pet_teacher_info_box {
				display: flex;
				align-items: center;
				margin-top: 24rpx;

				.pet_teacher_img {
					width: 120rpx;
					height: 120rpx;
					border-radius: 50%;
				}

				.pet_teacher_info {
					margin-left: 32rpx;
					width: calc(100% - 120rpx - 32rpx);

					.pet_teacher_name {
						font-weight: bold;
						font-size: 36rpx;
						color: #1b2120;
					}

					.pet_teacher_tel {
						font-weight: 400;
						font-size: 26rpx;
						color: #7c807f;
						margin-top: 16rpx;
					}
				}
			}
		}

		.order_item_box {
			width: 100%;
			background: #ffffff;
			border-radius: 24rpx;
			padding: 64rpx 32rpx 40rpx;
			box-sizing: border-box;
			margin-bottom: 24rpx;
			position: relative;

			.association_tips {
				position: absolute;
				top: 0;
				left: 0;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 8rpx 18rpx;
				box-sizing: border-box;
				background: #6363ff;
				border-radius: 24rpx 0rpx 24rpx 0rpx;
				font-weight: 400;
				font-size: 26rpx;
				color: #ffffff;
			}

			.order_info_status_box {
				.name_status {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.name_transfer {
						display: flex;
						flex-direction: row;
					}

					.user_avatar_pic {
						width: 48rpx;
						height: 48rpx;
						border-radius: 50%;
						background: #f9f6f6;
						margin-right: 16rpx;
					}

					.studio_name {
						font-weight: bold;
						font-size: 32rpx;
						color: #1b2120;
					}

					.order_status {
						font-weight: 400;
						font-size: 26rpx;
						color: #6363ff;
					}
				}

				.order_date {
					font-weight: 400;
					font-size: 24rpx;
					color: #808080;
					margin-top: 10rpx;
				}
			}

			.studio_name_text {
				font-weight: bold;
				font-size: 26rpx;
				color: #1b2120;
				margin-top: 48rpx;
				border-bottom: 1rpx solid #e4e6e6;
				padding-bottom: 24rpx;
			}

			.order_server_info {
				display: flex;
				justify-content: space-between;
				margin-top: 24rpx;

				.server_info_box {
					display: flex;
					align-items: center;
					flex-direction: row;

					.server_img {
						width: 120rpx;
						height: 120rpx;
						border-radius: 12rpx;
					}

					.name_price {
						margin-left: 16rpx;

						.server_name {
							font-weight: bold;
							font-size: 32rpx;
							color: #1b2120;
						}

						.specs_price {
							font-weight: 400;
							font-size: 26rpx;
							color: #7c807f;
							margin-top: 24rpx;

							.server_specs {
							}

							.server_price {
							}
						}
					}
				}

				.multiple_specs_scroll {
					white-space: nowrap;
					width: calc(100% - 128rpx);

					.server_info_box {
						display: inline-block;
						width: 120rpx;
						height: 120rpx;
						border-radius: 12rpx;
						position: relative;
						margin-right: 16rpx;

						.server_img {
							width: 120rpx;
							height: 120rpx;
							border-radius: 12rpx;
						}

						.specs_box {
							position: absolute;
							top: 8rpx;
							left: 8rpx;
							max-width: 98rpx;
							padding: 4rpx;
							box-sizing: border-box;
							background: #f9f6f6;
							border-radius: 4rpx;
							font-weight: 400;
							font-size: 18rpx;
							color: #1b2120;
							white-space: nowrap;
							overflow: hidden;
							text-overflow: ellipsis;
						}

						.server_price {
							position: absolute;
							bottom: 0;
							right: 0;
							padding: 8rpx 10rpx;
							box-sizing: border-box;
							background: rgba(0, 0, 0, 0.35);
							border-radius: 24rpx 0rpx 24rpx 0rpx;
							font-weight: bold;
							font-size: 18rpx;
							color: #ffffff;
						}
					}
				}

				.order_price_box {
					width: 128rpx;
					padding: 0 16rpx;
					box-sizing: border-box;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					box-shadow: -12rpx 0 20rpx -18rpx rgba(0, 0, 0, 0.2);

					.order_price {
						font-weight: bold;
						font-size: 28rpx;
						color: #1b2120;
					}

					.pay_text {
						font-weight: 400;
						font-size: 24rpx;
						color: #7c807f;
						margin-top: 16rpx;
					}
				}
			}

			.order_other_info_box {
				width: 100%;
				border-radius: 16rpx;
				border: 2rpx solid #f9f6f6;
				padding: 32rpx 24rpx;
				box-sizing: border-box;
				margin-top: 16rpx;

				.other_info_item {
					display: flex;
					flex-direction: row;
					margin-bottom: 40rpx;

					.other_label {
						width: 96rpx;
						font-weight: bold;
						font-size: 24rpx;
						color: #5c5e5e;
					}

					.other_value {
						max-width: calc(100% - 96rpx - 16rpx);
						font-weight: 400;
						font-size: 24rpx;
						color: #7c807f;
						margin-left: 16rpx;
					}
				}

				.other_info_item:last-child {
					margin-bottom: 0;
				}
			}
		}

		.value_added_services_box {
			width: 100%;
			background: #ffffff;
			border-radius: 24rpx;
			padding: 32rpx;
			box-sizing: border-box;
			margin-top: 24rpx;

			.add_title {
				font-weight: bold;
				font-size: 26rpx;
				color: #1b2120;
				padding-bottom: 24rpx;
				box-sizing: border-box;
				border-bottom: 1rpx solid #e4e6e6;
			}

			.add_order_list_box {
				.add_order_item {
					display: flex;
					flex-direction: row;
					margin-top: 48rpx;

					.add_server_img {
						width: 120rpx;
						height: 120rpx;
						border-radius: 24rpx;
					}

					.add_server_info {
						width: calc(100% - 120rpx - 32rpx);
						padding-bottom: 48rpx;
						border-bottom: 1rpx solid #e4e6e6;
						margin-left: 32rpx;

						.add_server_name {
							font-weight: bold;
							font-size: 30rpx;
							color: #1b2120;
							margin-top: 10rpx;
						}

						.add_server_price {
							display: flex;
							justify-content: space-between;
							margin-top: 38rpx;

							.price {
								font-weight: 400;
								font-size: 26rpx;
								color: #7c807f;
							}

							.times {
								font-weight: bold;
								font-size: 26rpx;
								color: #1b2120;
							}
						}

						.add_server_pets {
							width: 100%;
							background: #f5f6f7;
							border-radius: 12rpx;
							padding: 24rpx 24rpx 8rpx 24rpx;
							box-sizing: border-box;
							margin-top: 16rpx;
							line-height: 1;

							.pet_name_date {
								display: inline-block;
								margin-bottom: 24rpx;
								font-weight: 400;
								font-size: 24rpx;
								color: #7c807f;
								margin-right: 24rpx;
							}
						}
					}
				}

				.add_order_item:last-child {
					.add_server_info {
						border-bottom: none;
						padding-bottom: 0;
					}
				}
			}
		}

		.order_data_info_box {
			width: 100%;
			background: #ffffff;
			border-radius: 24rpx;
			padding: 40rpx 32rpx;
			box-sizing: border-box;
			margin-bottom: 24rpx;

			.income_structure {
				font-weight: bold;
				font-size: 28rpx;
				color: #5c5e5e;
				padding-bottom: 32rpx;
				border-bottom: 1rpx solid #e4e6e6;
				margin-bottom: 32rpx;
			}

			.order_data_info {
				display: flex;
				justify-content: space-between;
				margin-bottom: 40rpx;

				.order_data_label {
					display: flex;
					align-items: center;
					font-weight: 400;
					font-size: 28rpx;
					color: #5c5e5e;
				}

				.studio_img {
					width: 48rpx;
					height: 48rpx;
					border-radius: 50%;
					margin-right: 8rpx;
				}

				.order_data_value {
					display: flex;
					align-items: center;
					font-weight: 400;
					font-size: 28rpx;
					color: #1b2120;

					.order_data_value_text {
						font-weight: 400;
						font-size: 28rpx;
						color: #1b2120;
					}

					.dividing_line {
						width: 2rpx;
						height: 28rpx;
						margin: 0 20rpx;
						background: #1b2120;
					}

					.copy_btn {
						font-weight: 400;
						font-size: 28rpx;
						color: #ff6084;
						text-decoration-line: underline;
					}
				}
			}

			.user_income {
				padding-top: 17px;
				border-top: 1px solid #e4e6e6;
			}

			.order_total {
				font-weight: bold;

				.order_data_label,
				.order_data_value {
					color: #1b2120;
					font-weight: bold;
				}
			}

			.order_data_info:last-child {
				margin-bottom: 0;
			}
		}
	}

	.footer_btn_box:not(:empty) {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		display: flex;
		justify-content: flex-end;
		margin-top: 28rpx;
		background: #ffffff;
		border-top: 1rpx solid #e4e6e6;
		padding: 8rpx 34rpx;
		padding-bottom: calc(constant(safe-area-inset-bottom) + 8rpx);
		padding-bottom: calc(env(safe-area-inset-bottom) + 8rpx);
		box-sizing: border-box;

		.hollow_btn {
			box-sizing: border-box;
			width: 222rpx;
			height: 88rpx;
		}

		.solid_btn {
			box-sizing: border-box;
			width: 222rpx;
			height: 88rpx;
		}

		.btn_mg {
			margin-right: 8rpx;
		}

		.btn_mg:last-child {
			margin-right: 0;
		}
	}

	.footer_btn_box:empty {
	}
}

.refuse_pop {
	width: 100%;
	background: #f9f6f6;
	border-radius: 24rpx 24rpx 0rpx 0rpx;
	padding: 68rpx 32rpx;
	box-sizing: border-box;

	.pop_title_box {
		display: flex;
		justify-content: space-between;

		.pop_title {
			font-weight: bold;
			font-size: 40rpx;
			color: #1b2120;
		}

		.closeempty_icon {
			color: #1b2120;
			font-weight: bold;
		}
	}

	.refuse_reason_box {
		width: 100%;
		background: #ffffff;
		border-radius: 24rpx;
		padding: 32rpx 32rpx 0;
		box-sizing: border-box;
		margin-top: 52rpx;
		margin-bottom: 42rpx;

		.refuse_title {
			font-weight: 400;
			font-size: 32rpx;
			color: #1b2120;
		}

		.reason_item_box {
			padding: 44rpx 0;
			box-sizing: border-box;
			border-bottom: 1px solid #e4e6e6;

			.reason_text_box {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.reason_text {
					font-weight: 400;
					font-size: 32rpx;
					color: #1b2120;
				}

				.select_img {
					width: 40rpx;
					height: 40rpx;
					border-radius: 50%;
				}
			}

			.refuse_textarea {
				width: 100%;
				height: 236rpx;
				background: #f9f6f6;
				border-radius: 16rpx 16rpx 16rpx 16rpx;
				padding: 32rpx;
				box-sizing: border-box;
				font-weight: 400;
				font-size: 30rpx;
				color: #1b2120;
			}
		}

		.reason_item_box:last-child {
			border-bottom: none;
		}
	}

	.footer_btn_box {
		width: 100%;
		background: #ffffff;
		padding: 8rpx 24rpx 8rpx 40rpx;
		box-sizing: border-box;
		position: fixed;
		bottom: 0;
		left: 0;
		padding-bottom: calc(8rpx + var(--safe-area-bottom));

		.confirm_btn {
			width: 100%;
			height: 88rpx;
		}
	}
}

.m_r_8 {
	margin-right: 8rpx;
}
</style>
